package org.hank.compose_yyzs.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.bean.ProjectTreeNode
import org.hank.compose_yyzs.db.dao.ProjectDao
import java.util.Locale
import javax.inject.Inject

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/11/10 14:35
 *描述:
 */
@HiltViewModel
class SearchViewModel @Inject constructor(var projectDao: ProjectDao) : ViewModel() {
    var projectList: MutableStateFlow<MutableList<ProjectTreeNode>> = MutableStateFlow(ArrayList())
    var datas: MutableList<ProjectTreeNode> = ArrayList()
    var searchText = MutableStateFlow("")
    var searchFocs = MutableStateFlow(false)

    fun getProjectTree() {
        viewModelScope.launch(Dispatchers.IO) {
            datas = projectDao.filesList?.stateIn(viewModelScope)?.value ?: ArrayList()
            datas.forEach {
                addParentToChildren(it)
            }
            datas.forEach { addAreaName(it) }
            projectList.emit(datas)
        }
    }

    fun filterData(
        query: String
    ) {
        val filteredList = mutableListOf<ProjectTreeNode>()
        val map = hashMapOf<String, ProjectTreeNode>() // 用来合并的映射
        val expandSet = hashSetOf<String>() // 用来记录哪些item的parent需要展开
        if (query.isEmpty()) {
            viewModelScope.launch {
                //加载初始化数据
                getProjectTree()
            }
        } else {
            //datas是源数据
            for (item in datas) {
                if (item.name.lowercase(Locale.getDefault()).contains(query)) {
                    // 如果item的code已经在映射中，合并children
                    if (item.id.toString() in map) {
//                        val existing = map[item.code]!!
//                        existing.children?.addAll(item.children ?: emptyList())
                    } else {
                        // 否则，加入映射和过滤列表
                        map[item.id.toString()] = item
                        filteredList.add(item)
                    }
                    // 把item的parent的code加入到展开集合中
                    item.parent?.let { expandSet.add(it.id.toString()) }
                }
                // 如果item有children，调用递归函数搜索并加入到过滤列表中
                if (!item.children.isNullOrEmpty()) {
                    filteredList.addAll(searchChildren(item.children!!, query, expandSet))
                }
            }
            deepExpand(filteredList, expandSet)
            viewModelScope.launch {
                //显示修改后的数据列表
                projectList.emit(filteredList)
            }
        }
    }

    private fun deepExpand(filteredList: MutableList<ProjectTreeNode>, expandSet: HashSet<String>) {
        for (item in filteredList) {
            if (item.id.toString() in expandSet) {
                item.isExpand = true
            }
            if (item.children != null && item.children!!.size > 0) {
                deepExpand(item.children!!, expandSet)
            }
        }
    }

    // 一个递归函数，用来遍历每个item的children，并返回一个过滤后的子列表
    private fun searchChildren(
        children: MutableList<ProjectTreeNode>,
        query: String,
        expandSet: HashSet<String>
    ): MutableList<ProjectTreeNode> {
        val subList = mutableListOf<ProjectTreeNode>()
        for (child in children) {
            if (child.name.lowercase(Locale.getDefault()).contains(query)) {
                subList.add(child)
                // 把child的parent的code加入到展开集合中
                child.parent?.let { expandSet.add(it.id.toString()) }
            }
            // 如果child有children，递归搜索并加入到子列表中
            if (!child.children.isNullOrEmpty()) {
                subList.addAll(searchChildren(child.children!!, query, expandSet))
            }
        }
        return subList
    }

    private fun addParentToChildren(projectTreeNode: ProjectTreeNode) {
        if (!projectTreeNode.children.isNullOrEmpty()) {
            for (child in projectTreeNode.children!!) {
                child.parent = projectTreeNode
                addParentToChildren(child)
            }
        }
    }

    private fun addAreaName(projectTreeNode: ProjectTreeNode){
        if(projectTreeNode.parent!= null){
                projectTreeNode.areaName = projectTreeNode.parent!!.name
            if(projectTreeNode.parent!!.parent!=null)
                projectTreeNode.areaName = projectTreeNode.parent!!.parent!!.name +"-"+projectTreeNode.parent!!.name
        }
        if(!projectTreeNode.children.isNullOrEmpty()){
            projectTreeNode.children!!.forEach { addAreaName(it) }
        }
    }
}